<template>
  <div class="modal modal-blur fade" id="modal-add-machine" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
      <div class="modal-content">
        <form id="addMachineForm" class="needs-validation" novalidate>
          <div class="modal-header">
            <h5 class="modal-title">新增机器</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" @click="closeModal"></button>
          </div>
          <div class="modal-body">
            <div class="mb-3">
              <label class="form-label required">IP</label>
              <input type="text" 
                     class="form-control" 
                     name="ip" 
                     v-model="formData.ip"
                     placeholder="请输入IP"
                     maxlength="30"
                     required>
              <div class="invalid-feedback">
                请输入IP地址
              </div>
            </div>
            <div class="mb-3">
              <label class="form-label required">标签</label>
              <select class="form-select" 
                      id="label" 
                      name="label" 
                      v-model="formData.label"
                      required>
                <option value="">请选择标签</option>
                <option v-for="type in typeList" 
                        :key="type.value" 
                        :value="type.value">
                  {{ type.label }}
                </option>
              </select>
              <div class="invalid-feedback">
                请选择标签
              </div>
            </div>
            <div class="mb-3">
              <label class="form-label">用户名</label>
              <input type="text" 
                     class="form-control" 
                     name="username" 
                     v-model="formData.username"
                     placeholder="请输入用户名"
                     maxlength="50">
            </div>
            <div class="mb-3">
              <label class="form-label">密码</label>
              <input type="password" 
                     class="form-control" 
                     name="password" 
                     v-model="formData.password"
                     placeholder="请输入密码"
                     maxlength="50">
            </div>
            <div class="mb-3">
              <label class="form-label">备注</label>
              <textarea class="form-control" 
                        rows="3" 
                        name="remark" 
                        v-model="formData.remark"
                        maxlength="100"
                        placeholder="请输入备注"></textarea>
              <div class="text-muted small">最多输入100个字符</div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" 
                    class="btn btn-link link-secondary" 
                    data-bs-dismiss="modal"
                    @click="closeModal">
              取消
            </button>
            <button type="submit" 
                    class="btn btn-primary ms-auto"
                    @click="submitAddMachine">
              保存
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { Modal } from 'bootstrap';

const props = defineProps({
  typeList: {
    type: Array,
    required: true
  }
});

const emit = defineEmits(['add-success']);

const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;
const formData = reactive({
  ip: '',
  label: '',
  username: '',
  password: '',
  remark: ''
});

let addMachineModal;

onMounted(() => {
  addMachineModal = new Modal(document.getElementById('modal-add-machine'));
});

const openModal = () => {
  // 重置表单数据
  formData.ip = '';
  formData.label = '';
  formData.username = '';
  formData.password = '';
  formData.remark = '';
  // 重置表单验证状态
  const form = document.getElementById('addMachineForm');
  form.classList.remove('was-validated');
  form.reset();
  addMachineModal.show();
};

const closeModal = () => {
  addMachineModal.hide();
  // 重置表单数据
  formData.ip = '';
  formData.label = '';
  formData.username = '';
  formData.password = '';
  formData.remark = '';
  // 重置表单验证状态
  const form = document.getElementById('addMachineForm');
  form.classList.remove('was-validated');
  form.reset();
};

const submitAddMachine = async (event) => {
  event.preventDefault();
  event.stopPropagation();
  
  const form = document.getElementById('addMachineForm');
  form.classList.add('was-validated');
  
  if (!form.checkValidity()) {
    return;
  }

  try {
    const formDataToSend = new URLSearchParams();
    formDataToSend.append('ip', formData.ip);
    formDataToSend.append('label', formData.label);
    formDataToSend.append('username', formData.username);
    formDataToSend.append('password', formData.password);
    formDataToSend.append('remark', formData.remark);

    const response = await fetch(`${apiBaseUrl}/resident/machine/add`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: formDataToSend
    });
    
    const result = await response.json();
    if (result.success) {
      addMachineModal.hide();
      form.classList.remove('was-validated');
      form.reset();
      emit('add-success');
    } else {
      alert('添加失败：' + (result.message || '未知错误'));
    }
  } catch (error) {
    console.error('Add error:', error);
    alert('添加失败，请稍后重试！');
  }
};

defineExpose({
  openModal,
  closeModal
});
</script>

<style scoped>
.required:after {
  content: " *";
  color: red;
}

.form-control:invalid,
.form-select:invalid {
  border-color: #dc3545;
}

.form-control:invalid:focus,
.form-select:invalid:focus {
  border-color: #dc3545;
  box-shadow: 0 0 0 0.25rem rgba(220, 53, 69, 0.25);
}

.was-validated .form-control:invalid,
.was-validated .form-select:invalid {
  border-color: #dc3545;
  padding-right: calc(1.5em + 0.75rem);
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right calc(0.375em + 0.1875rem) center;
  background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}

.was-validated .form-control:valid,
.was-validated .form-select:valid {
  border-color: #198754;
  padding-right: calc(1.5em + 0.75rem);
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%23198754' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right calc(0.375em + 0.1875rem) center;
  background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}

.invalid-feedback {
  display: none;
  width: 100%;
  margin-top: 0.25rem;
  font-size: 0.875em;
  color: #dc3545;
}

.was-validated .form-control:invalid ~ .invalid-feedback,
.was-validated .form-select:invalid ~ .invalid-feedback {
  display: block;
}
</style> 